package cn.qingyun.gis.modules.express.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.qingyun.gis.common.Result;
import cn.qingyun.gis.exception.CommonException;
import cn.qingyun.gis.modules.express.entity.ExpressProofread;
import cn.qingyun.gis.modules.express.entity.dto.ExportExpressProofreadDto;
import cn.qingyun.gis.modules.express.request.ExpressProofreadRequest;
import cn.qingyun.gis.modules.express.request.ExpressQueryRequest;
import cn.qingyun.gis.modules.express.request.NearbyChannelRequest;
import cn.qingyun.gis.modules.express.request.QueryRequest;
import cn.qingyun.gis.modules.express.service.IExpressInfoTotalService;
import cn.qingyun.gis.modules.express.service.IExpressProofreadService;
import cn.qingyun.gis.modules.init.system.annotation.AutoLog;
import cn.qingyun.gis.modules.init.system.base.controller.BasicController;
import cn.qingyun.gis.modules.init.system.entity.SysUser;
import cn.qingyun.gis.modules.init.system.mapper.SysUserMapper;
import cn.qingyun.gis.modules.init.system.query.QueryGenerator;
import cn.qingyun.gis.modules.init.utils.JwtUtil;
import cn.qingyun.gis.modules.scenes.service.IUniAddrRegionService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.util.Arrays;

/**
 * <p>
 * 快递地址勘误 前端控制器
 * </p>
 *
 * @author miyunguo
 * @since 2023-07-27
 */
@RestController
@RequestMapping("/app/express")
@Api(value = "快递地址勘误", tags = {"快递地址勘误"})
@Slf4j
public class ExpressProofreadController extends BasicController<ExpressProofread, IExpressProofreadService> {
    @Resource
    private IExpressProofreadService iExpressProofreadService;
    @Resource
    private IExpressInfoTotalService iExpressInfoTotalService;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private HttpServletRequest request;
    @Resource
    private IUniAddrRegionService IUniAddrRegionService;

    @GetMapping("/query")
    @ApiOperation("快递地址未勘误列表查询-需传入网格编码、工号（非必填）、区域权限、关键字（非必填）")
    public Result<?> queryList(@Validated ExpressQueryRequest request) {
        return Result.okData(iExpressProofreadService.queryList(request));
    }

    @GetMapping("/querytotal")
    @ApiOperation("快递地址已勘误列表查询-需传入网格编码、工号（非必填）、区域权限、关键字（非必填）")
    public Result<?> queryTotalList(@Validated ExpressQueryRequest request) {
        return Result.okData(iExpressInfoTotalService.queryTotalList(request));
    }

    @PostMapping("/nearbyChannel")
    @ApiOperation("附近渠道")
    public Result<?> nearbyChannel(@Validated @RequestBody NearbyChannelRequest request) {
        return Result.okData(iExpressProofreadService.nearbyChannel(request));
    }

    @PostMapping("/selectById")
    @ApiOperation("根据id获取站点信息")
    public Result<?> selectById(@RequestBody QueryRequest request) {
        if (request.getTypeCode() == 0) {
            return Result.okData(iExpressProofreadService.queryExpressById(request));
        }
        if (request.getTypeCode() == 1) {
            return Result.okData(iExpressProofreadService.queryTakeawayById(request));
        }
        if (request.getTypeCode() == 2) {
            return Result.okData(iExpressProofreadService.queryCarById(request));
        }
        return Result.error("根据id数据查询失败");
    }

    @GetMapping("/regionList")
    @ApiOperation("工号级联区域权限列表查询")
    public Result<?> regionList(@RequestParam("telNum") String telNum) {
        return Result.okData(iExpressProofreadService.regionList(telNum));
    }

    @GetMapping("/queryRegion")
    @ApiOperation("级联区域权限列表查询")
    public Result<?> queryRegion(String token) {
        if (ObjectUtil.isEmpty(JwtUtil.getUsername(token))) {
            throw new CommonException("token解析失败");
        }
        return Result.okData(iExpressProofreadService.regionList(JwtUtil.getUsername(token)));
    }

    @GetMapping("/getRegionList")
    @ApiOperation("级联区域权限列表查询")
    public Result<?> getRegionList() {
        return Result.okData(iExpressProofreadService.getRegionList());
    }

    @GetMapping("/app/getRegionListNew")
    @ApiOperation("app级联区域权限列表查询")
    public Result<?> getAppRegionListNew(@RequestParam(value = "regionCode",required = true) String regionCode,
                                         @RequestParam(value = "regionName",required = true)String regionName,
                                         @RequestParam(value = "roleType",required = true)Integer roleType) {
        return Result.okData(iExpressProofreadService.getAppRegionListNew(regionCode,regionName,roleType));
    }

    @ApiOperation("获取所有网格数据")
    @GetMapping("/getGridList")
    public Result<?> getGridList(@RequestParam @NotNull(message = "区县编码不能为空") String code) {
        return Result.okData(iExpressProofreadService.getGridList(code));
    }

    @GetMapping("/sonRegionList")
    @ApiOperation("根据父节点编码获取子节点列表")
    public Result<?> sonRegionList(@RequestParam("code") String code) {
        return Result.okData(iExpressProofreadService.sonRegionList(code));
    }

    @GetMapping("/sonRegionListNew")
    @ApiOperation("摸排根据父节点编码获取子节点列表")
    public Result<?> sonRegionListNew(@RequestParam("code") String code) {
        return Result.okData(IUniAddrRegionService.sonRegionListNew(code));
    }

    @GetMapping("/matchBelongGrid")
    @ApiOperation("匹配应属网格")
    public Result<?> matchBelongGrid() {
        iExpressProofreadService.matchBelongGrid();
        return Result.okData("稍等，正在匹配应属网格");
    }

    @PostMapping("/proofread")
    @ApiOperation("快递地址勘误")
    public Result<?> proofread(@Validated @RequestBody ExpressProofreadRequest request) {
        return Result.okData(iExpressProofreadService.expressProofread(request));
    }

    @GetMapping("/matchGrid")
    @ApiOperation("匹配快递地址-地市、区县、网格、微网格")
    public Result<?> matchGrid() {
        iExpressProofreadService.matchGrid();
        return Result.okData("正在将快递数据进行业务区划匹配~~");
    }


    //  后台管理


    /**
     * 分页列表查询
     *
     * @param expressProofread
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "快递勘误表-分页列表查询")
    @ApiOperation(value = "快递勘误表-分页列表查询", notes = "快递勘误表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(ExpressProofread expressProofread,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<ExpressProofread> queryWrapper = QueryGenerator.initQueryWrapper(expressProofread, req.getParameterMap());
        queryWrapper.lambda().orderByDesc(ExpressProofread::getUpdateTime);
        Page<ExpressProofread> page = new Page<>(pageNo, pageSize);
        IPage<ExpressProofread> pageList = iExpressProofreadService.page(page, queryWrapper);
        return Result.okData(pageList);
    }

    /**
     * 分页列表查询
     *
     * @param expressProofread
     * @param pageNo
     * @param pageSize
     * @param request
     * @return
     */
    @AutoLog(value = "快递明细表-分页列表查询")
    @ApiOperation(value = "快递明细表-分页列表查询", notes = "快递明细表-分页列表查询")
    @GetMapping(value = "/detailList")
    public Result<?> queryPageDetailList(ExpressProofread expressProofread,
                                         @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                         HttpServletRequest request) {

        // 获取当前用户信息
        String currentUserName = JwtUtil.getUserNameByToken(request);
        // 根据用户信息查询区域编码
        SysUser user = sysUserMapper.selectOne(new QueryWrapper<SysUser>().lambda().
                select(SysUser::getRegionCode).
                eq(SysUser::getUsername, currentUserName));
        String regionCode;
        if ("0000SD".equals(user.getRegionCode())) { // 当前省级配置工号
            regionCode = null;
        } else {
            regionCode = user.getRegionCode();
        }
        Page<ExportExpressProofreadDto> page = new Page<>(pageNo, pageSize);
        IPage<ExportExpressProofreadDto> pageList = iExpressProofreadService.queryDetailList(page, null, regionCode);
        return Result.okData(pageList);
    }

    /**
     * 添加
     *
     * @param expressProofread
     * @return
     */
    @AutoLog(value = "快递勘误表-添加")
    @ApiOperation(value = "快递勘误表-添加", notes = "快递勘误表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody ExpressProofread expressProofread) {
        expressProofread.setCreateTime(DateUtil.date());
        expressProofread.setUpdateTime(DateUtil.date());
        iExpressProofreadService.save(expressProofread);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param expressProofread
     * @return
     */
    @AutoLog(value = "快递勘误表-编辑")
    @ApiOperation(value = "快递勘误表-编辑", notes = "快递勘误表-编辑")
    @PostMapping(value = "/edit")
    public Result<?> edit(@RequestBody ExpressProofread expressProofread) {
        iExpressProofreadService.updateById(expressProofread);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "快递勘误表-通过id删除")
    @ApiOperation(value = "快递勘误表-通过id删除", notes = "快递勘误表-通过id删除")
    @GetMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id") String id) {
        iExpressProofreadService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "快递勘误表-批量删除")
    @ApiOperation(value = "快递勘误表-批量删除", notes = "快递勘误表-批量删除")
    @GetMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids") String ids) {
        this.iExpressProofreadService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "快递勘误表-通过id查询")
    @ApiOperation(value = "快递勘误表-通过id查询", notes = "快递勘误表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id") String id) {
        ExpressProofread expressProofread = iExpressProofreadService.getById(id);
        if (expressProofread == null) {
            return Result.error("未找到对应数据");
        }
        return Result.okData(expressProofread);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param expressProofread
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ExpressProofread expressProofread) {
        return super.exportXls(request, expressProofread, ExpressProofread.class, "快递勘误表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ExpressProofread.class);
    }
}
